package com.founder.bdyx.modules.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.founder.bdyx.PdfReport;
import com.founder.bdyx.core.entity.ProcessResult;
import com.founder.bdyx.core.pdfUtil.CreateTemplate;
import com.founder.bdyx.core.result.PageResult;
import com.founder.bdyx.core.util.DictConvertUtil;
import com.founder.bdyx.core.util.FileUtil;
import com.founder.bdyx.core.util.SourcePath;
import com.founder.bdyx.modules.sys.model.ApplyInfo;
import com.founder.bdyx.modules.sys.service.ApplyInfoService;
import com.founder.bdyx.modules.sys.service.SendService;
import com.founder.bdyx.wxpro.conf.WxConfig;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.founder.bdyx.core.entity.ProcessResult.ERROR;

@RestController
@RequestMapping("/sys/send")
public class SendController {
    Log log = LogFactory.getLog(SendController.class);

    @Autowired
    private ApplyInfoService applyInfoService;
    @Autowired
    private SendService sendService;
    @Autowired
    private WxConfig wxConfig;
    @Value("${pdf_save_path}")
    private String PDF_SAVE_PATH;

    @ApiOperation(value = "审批列表视图",notes = "审批列表视图")
    @GetMapping("/list")
    public ModelAndView list() {
        return new ModelAndView("/modules/send/list");
    }

    @ApiOperation(value = "获取审核列表",notes = "获取审核列表")
    @RequestMapping(value = "",method = RequestMethod.GET)
    public List<ApplyInfo> getAll(@ApiParam(name = "keyword",value="查询字段",required = false) String keyword, String paystatus, String isPrint) {
        List<ApplyInfo> applyInfos = applyInfoService.getSendAll(keyword,paystatus,isPrint);
        if(applyInfos != null && applyInfos.size()>0)
            DictConvertUtil.converter(applyInfos);
//        return new PageResult(new PageInfo<ApplyInfo>(applyInfos));
        return applyInfos;
    }

    @ApiOperation(value = "申请详情视图",notes = "申请详情视图")
    @RequestMapping(value = "/form",method = RequestMethod.GET)
    public ModelAndView form() {
        return new ModelAndView("/modules/send/form");
    }

    @ApiOperation(value = "获取申请详细信息",notes = "获取申请详细信息")
    @PostMapping(value = "/view/{id}")
    public ApplyInfo view(@ApiParam(name = "id", value = "申请单id", required = true) @PathVariable String id){
        ApplyInfo applyInfo = applyInfoService.getByAppId(id);
        DictConvertUtil.converter(applyInfo);
        return applyInfo;
    }

    @ApiOperation(value = "邮寄打印",notes = "邮寄打印")
    @PostMapping(value = "/print/{id}")
    public JSONObject print(@ApiParam(name = "id", value = "申请单id", required = true) @PathVariable Integer id, HttpServletRequest request){
        try {
            File file = sendService.execOrder(id,request);
            JSONObject obj = new JSONObject();
            if(file != null){
                obj.put("code","ok");
                String url = SourcePath.execute(wxConfig.basePath,file.getName());
                obj.put("url",url);
            }else{
                obj.put("code","error");
                obj.put("url","");
                obj.put("msg","生成执行单失败");
            }
            return obj;
        }catch (Exception e){
            log.error("执行单生成失败," ,e);
        }
        JSONObject obj = new JSONObject();
        obj.put("code","error");
        obj.put("url","");
        obj.put("msg","生成执行单失败");
        return obj;
    }

    @ApiOperation(value = "批量打印",notes = "批量打印")
    @PostMapping(value = "/batchPrint")
    public JSONObject batchPrint(@ApiParam(name = "ids", value = "申请单id数组", required = true) @RequestParam("ids[]") Integer[] ids,
                                 HttpServletRequest request){
        try {
            List<File> files = sendService.batchExecOrder(ids,request);
            String fileName = new Date().getTime() + "merge.pdf";
            String filePath = PDF_SAVE_PATH + fileName;
            Boolean retFlag = CreateTemplate.mergePdfFiles(files,filePath);
            JSONObject obj = new JSONObject();
            if(retFlag){
                obj.put("code","ok");
                String url = SourcePath.execute(wxConfig.basePath,fileName);
                obj.put("url",url);
            }else{
                obj.put("code","error");
                obj.put("url","");
                obj.put("msg","批量打印失败");
            }
            return obj;
        }catch (Exception e){
            log.error("批量打印失败" , e);
            JSONObject obj = new JSONObject();
            obj.put("code","error");
            obj.put("url","");
            obj.put("msg","批量打印失败");
            return obj;
        }
    }

    @ApiOperation(value = "批量下载",notes = "批量下载")
    @PostMapping(value = "/batchDownLoad")
    public void batchNotice(Integer[] ids, HttpServletResponse response, HttpServletRequest request){
        try {
            //如果选中一条 直接下载
            if(ids.length == 1){
                File file = sendService.execOrder(ids[0],request);
                if(file.exists()){
                    FileUtil.downloadFile(response,file);
                }
                return;
            }

            List<File> files = sendService.batchExecOrder(ids,request);
            FileUtil.downLoadFiles(files,response);

        }catch (Exception e){
            log.error("执行单生成下载失败" , e);
        }
    }
}
